const { name } = require('@/config/ProjectTitle')
import Vue from 'vue'
import store from '@/store'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

import routes from './modules/index'

export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    hidden: true,
    meta: {
      title: '登录'
    }
  }
]

export const asyncRoutes = [
  ...routes,
  // 404 page must be placed at the end !!!
  {
    path: '*',
    name: '404',
    component: () => import('@/views/404Page.vue'),
    hidden: true,
    meta: {}
  }
]

const createRouter = () =>
  new VueRouter({
    routes: constantRoutes,
    scrollBehavior: () => ({ y: 0 })
  })

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

const whiteList = ['/login']

const router = createRouter()

router.beforeEach(async (to, from, next) => {
  document.title = to.meta.title ? name + '-' + to.meta.title : name

  const hasToken = getToken()
  await store.dispatch('permission/applicationConfiguration')

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const hasGetUserInfo = store.getters.userName
      // 是否有该用户
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          await store.dispatch('user/getInfo')

          if (store.getters.policies) {
            // 更新用户路由
            const grantedPolicies = store.getters.policies
            const accessRoutes = await store.dispatch(
              'permission/generateRoutes',
              grantedPolicies
            )
            router.addRoutes(accessRoutes)
          }
          next({ ...to, replace: true })
        } catch (error) {
          await store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
  }
})

export default router
